package com.saascloud.web.core.filter;


import com.saascloud.Constants;
import com.saascloud.core.saas.SaasContextUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/5/19 9:28
 * @Version: 1.0
 * @Description:提供从request对象获取租户信息能力，一般是内部
 */
public class SaasContextUtilFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            if (servletRequest instanceof HttpServletRequest) {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                String token = httpServletRequest.getHeader(Constants.HttpHeader.TOKEN);
                String tenantId = httpServletRequest.getHeader(Constants.HttpHeader.TENANT_ID);
                String traceId = httpServletRequest.getHeader(Constants.HttpHeader.TRACE_ID);
                SaasContextUtil.setTenantId(tenantId);
                SaasContextUtil.setToken(token);
                SaasContextUtil.setTraceId(traceId);
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SaasContextUtil.remove();
        }
    }
}
